package thread;

import java.util.Random;

public class practice1 {
    //给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
    //实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
    //其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
    //最终再汇总两个和, 进行相加
    //记录程序的执行时间.

        private static final int ARRAY_SIZE = 10_000_000; // 1000万长度
        private static int[] array = new int[ARRAY_SIZE];
        private static long evenSum = 0; // 偶数下标和
        private static long oddSum = 0;  // 奇数下标和

        // 计算偶数下标的线程
        static class EvenIndexSumTask implements Runnable {
            @Override
            public void run() {
                for (int i = 0; i < ARRAY_SIZE; i += 2) {
                    evenSum += array[i]; // 累加偶数索引元素
                }
            }
        }

        // 计算奇数下标的线程
        static class OddIndexSumTask implements Runnable {
            @Override
            public void run() {
                for (int i = 1; i < ARRAY_SIZE; i += 2) {
                    oddSum += array[i]; // 累加奇数索引元素
                }
            }
        }

        public static void main(String[] args) throws InterruptedException {
            Random random = new Random();
            for (int i = 0; i < ARRAY_SIZE; i++) {
                array[i] = random.nextInt(100) + 1;
            }


            long startTime = System.currentTimeMillis();


            Thread evenThread = new Thread(new EvenIndexSumTask());
            Thread oddThread = new Thread(new OddIndexSumTask());
            evenThread.start();
            oddThread.start();


            evenThread.join();
            oddThread.join();


            long totalSum = evenSum + oddSum;

            // 6. 记录结束时间并计算耗时
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;


            System.out.println("偶数下标和: " + evenSum);
            System.out.println("奇数下标和: " + oddSum);
            System.out.println("总和: " + totalSum);
            System.out.println("执行时间: " + duration );
        }

}
